import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTrans extends ServerSocket {

    private static final int Int_ServerPort = 9999;
    private ServerSocket Soc_Server;
    private Socket Soc_Accept;

    public static void main(String[] args) {
        try {

            new ServerTrans().Fn_SrvSocket();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //构造函数
    public ServerTrans() throws Exception {
        Soc_Server = new ServerSocket(Int_ServerPort);

    }

    //创建服务端Socket
    public void Fn_SrvSocket() throws Exception {
        try {
            String Str_Tmp;
            File File_New=null;

            while (true) {
                System.out.println("========等待连接==========");
                Soc_Accept = Soc_Server.accept();
                System.out.println("Client IP:" + Soc_Accept.getInetAddress() + " Accept");

                BufferedReader BuffRcv = new BufferedReader(
                        new InputStreamReader(Soc_Accept.getInputStream()));

                while ((Str_Tmp = BuffRcv.readLine()) != null) {
                    if (Str_Tmp.startsWith("File@")) {
                        Str_Tmp = Str_Tmp.substring(5);
                        File_New = new File(Str_Tmp + ".tmp");
                        if (File_New.exists()) {
                            File_New.delete();
                        } else {
                            File_New.createNewFile();
                        }
                        //System.out.println(Str_Tmp);
                    } else {
                        BufferedWriter BuffWrite = new BufferedWriter(
                                new FileWriter(File_New,true));
                        BuffWrite.write(Str_Tmp+"\r");
                        BuffWrite.close();
                        System.out.println(Str_Tmp);
                    }


                }
                //返回成功信息
                Str_Tmp = "File Transfer Success!";
                BufferedWriter BuffRsp = new BufferedWriter(
                        new OutputStreamWriter(Soc_Accept.getOutputStream()));
                BuffRsp.write(Str_Tmp);
                BuffRsp.flush();
                BuffRsp.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Soc_Accept.close();
            Soc_Server.close();
        }
    }


}
